﻿angular.module('starter')
// 账户登录
.controller("accountloginCtrl", function ($scope, $state, $ionicLoading, $ionicPopup, authService, accountService, $ionicHistory, $ionicTabsDelegate) {
    $scope.$on("$ionicView.beforeEnter", function () {
        if (authService.authentication.isAuth) {
            console.log("已经登录了, 正在为你跳转到...")
            $state.go('home');
            return;
        }
    });

    $ionicHistory.clearHistory();

    $ionicTabsDelegate.showBar(false);

    var ele_psdInput = $("#account_login .item-input input.password");
    var ele_eye = $("#account_login .psd .eye");
    ele_eye.on("click", function () {
        var state = $(this).attr("state");
        if (state === "off") {
            ele_psdInput.attr("type", "text");
            ele_eye.attr("state", "on");
            ele_eye.removeClass("icon-mimayincang").addClass("icon-mimakejian");
        } else {
            ele_psdInput.attr("type", "password");
            ele_eye.attr("state", "off");
            ele_eye.removeClass("icon-mimakejian").addClass("icon-mimayincang");
        }
    });
    $scope.inputChange = function () {
        var conChange = $("#account_login .inputInfor input").val();
        var quxiao = $("#account_login .inputInfor .quxiao");
        if (conChange == "") {
            quxiao.hide();
        } else {
            quxiao.show();
        }
    }
    $scope.quxiaoFn = function () {
        $("#account_login .inputInfor input").val("");
        $("#account_login .inputInfor .quxiao").hide();
    }
    $scope.loginData = {
        userName: '',
        password: ''
    };

    $scope.login = function () {
        var userName = $scope.loginData.userName;
        var password = $scope.loginData.password;

        if (userName.length == 0) {
            $ionicPopup.alert({
                title: '登录失败',
                template: '用户名不能为空'
            });
            return;
        }
        if (password.length == 0) {
            $ionicPopup.alert({
                title: '登录失败',
                template: '密码不能为空'
            });
            return;
        }

        $ionicLoading.show({
            template: '登录中...'
        });
        authService.login($scope.loginData).then(function (response) {
            // 登录成功
            console.log("登录成功, 正在为你跳转到...");
            accountService.User().then(function (response) {
                $ionicLoading.hide();
                console.log(response);
                $state.go('home');
            }, function (err) {
                console.log(err);
                $ionicLoading.hide();
            });

        }, function (err) {
            console.log(err);
            $ionicLoading.hide();
            $ionicPopup.alert({
                title: '登录失败',
                template: '请检查您填写的登陆信息！'
            });
            $scope.loginData.userName = "";
            $scope.loginData.password = "";
        });
    }
});